import { cookie } from '../../public/cookieFnNew.js';
import { ajax } from '../../public/promiseAjax.js'
import * as obj from '../public.js';
import { add } from './addCart.js';
const o = obj.default;
const goods = o.$('.goods')
const li = o.$$('.c_nav ul li')
const ul = o.$('.c_nav ul')
let idx = 0;
let first;
// console.log(shopCart)
// const shopCart = o.$('.icon-31gouwuche')
// shopCart.onclick = function () {
//   console.log(shopCart)
//   location.href = 'http://localhost:3000/html/shopcart.html'
// }
// 食品数据加载
ajax({
  url: 'http://10.11.55.120:3000/food',
}).then(res => {
  const data = JSON.parse(res);
  let str = '';
  console.log(data)
  data.forEach(val => {
    if(val.freeShipping === '不包邮'){
      str += ` <div class="con_goods">
      <img src="${val.imgs}" alt="">
      <div class="s_name">￥${val.pricec} <i style="display:none">${val.freeShipping}</i> <span>${val.buyers}人付款</span></div>
      <p>${val.name}</p>
      <div class="shop">${val.merchant}<em>${val.shippingPlace}</em></div>
      <input type="button" value="+" class="addCart"></input>
    </div>`
    }else{
      str += ` <div class="con_goods">
      <img src="${val.imgs}" alt="">
      <div class="s_name">￥${val.pricec} <i>${val.freeShipping}</i> <span>${val.buyers}人付款</span></div>
      <p>${val.name}</p>
      <div class="shop">${val.merchant}<em>${val.shippingPlace}</em></div>
      <input type="button" value="+" class="addCart"></input>
    </div>`
    }

  });

  // 商品信息添加到页面
  goods.innerHTML = str
  goods.onclick = function (eve) {
    const e = eve || window.event;
    const target = e.target || window.event;
    const li = o.$$('.addCart');
    const lis = [...li];
    let i = 0;
    lis.filter(val => val.index = i++)
    if (target.className === 'addCart') {
      const idx = target.index;
      const petCart = cookie.getCookie('petUserD');
      let userTel;
      let id;
      // 获取用户信息
      if (petCart) {
        petCart.split(',').forEach(val => {
          const a = val.split(':');
          if (a[0] === 'tel') {
            userTel = a[1]
          }
        })
      }
      ; (async () => {
        const obj = {};
        for (let t in data[idx]) {
          obj[t] = data[idx][t]
        }
        first = await ajax({
          url: 'http://localhost/:3000/getUser',
          method: 'get',
          data: {
            userTel,
          },
        }).then(res => {
          return JSON.parse(res).data
        });

        console.log(first)
        if (first.length === 0 && !first[0]) {
          obj.num = 1;
          obj.check = true;
          first.push(obj)
          // 用户购物车没有数据，添加数据
          ajax({
            url: 'http://localhost:3000/userShopCart',
            method: 'post',
            data: {
              userTel,
              shopCart: `${JSON.stringify(first)}`
            },
          })
        } else {
          id = data[idx]._id;
          const falg = first.some((val) => {
            if (val._id === id) {
              val.num++
              ajax({
                url: 'http://localhost:3000/userShopCart',
                method: 'post',
                data: {
                  userTel,
                  shopCart: JSON.stringify(first)
                }
              })
            }
            return val._id === id
          })
          if (!falg) {
            obj.check = true;
            obj.num = 1;
            first.push(obj)
            // 用户购物车没有数据，添加数据
            ajax({
              url: 'http://localhost:3000/userShopCart',
              method: 'post',
              data: {
                userTel,
                shopCart: `${JSON.stringify(first)}`
              },
            })
          }
        }






      }
      )();
    }
  }

  // console.log(o.$$('.addCart'))
  // goods.onclick = function (eve) {
  //   const e = eve || window.event;
  //   const target = e.target || window.event;
  //   const li = o.$$('.addCart');
  //   const lis = [...li];
  //   let i = 0;
  //   lis.filter(val => val.index = i++)
  //   if (target.className === 'addCart') {
  //     const idx = target.index;
  //     const petCart = cookie.getCookie('petUserD');
  //     let userTel;
  //     let id;
  //     // 获取用户信息
  //     if (petCart) {
  //       petCart.split(',').forEach(val => {
  //         const a = val.split(':');
  //         if (a[0] === 'tel') {
  //           userTel = a[1]
  //         }
  //         // if(a[0] === 'uId'){
  //         //   id = a[1]
  //         // }
  //       })
  //     }
  //     ; (async () => {
  //       const obj = {};
  //       for (let t in data[idx]) {
  //         obj[t] = data[idx][t]
  //       }
  //       first = await ajax({
  //         url: 'http://localhost:3000/getUser',
  //         method: 'get',
  //         data: {
  //           userTel,
  //           // shopCart: `[${JSON.stringify(obj)}]`
  //         },
  //       }).then(res => {
  //         return JSON.parse(res).data
  //       });
  //       console.log(first)
  //       if (first.length === 0 && !first[0]) {
  //         obj.num = 1
  //         first.push(obj)
  //         // 用户购物车没有数据，添加数据
  //         ajax({
  //           url: 'http://localhost:3000/userShopCart',
  //           method: 'post',
  //           data: {
  //             userTel,
  //             shopCart: `${JSON.stringify(first)}`
  //           },
  //         })
  //       } else {
  //         id = data[idx]._id;
  //         const falg = first.some((val) => {
  //           if (val._id === id) {
  //             val.num++
  //             ajax({
  //               url: 'http://localhost:3000/userShopCart',
  //               method: 'post',
  //               data: {
  //                 userTel,
  //                 shopCart: JSON.stringify(first)
  //               }
  //             })
  //           }
  //           return val._id === id
  //         })
  //         if (!falg) {
  //           obj.num = 1;
  //           first.push(obj)
  //           // 用户购物车没有数据，添加数据
  //           ajax({
  //             url: 'http://localhost:3000/userShopCart',
  //             method: 'post',
  //             data: {
  //               userTel,
  //               shopCart: `${JSON.stringify(first)}`
  //             },
  //           })
  //         }
  //       }






  //     }
  //     )();
  //   }
  // }
})



ul.onclick = function (eve) {
  const e = eve || window.event;
  const target = e.target || e.srcElement;
  const lis = Array.from(li)
  for (let i = 0; i < lis.length; i++) {
    lis[i].index = i
  }
  if (target.className !== 'cur' && target.tagName === 'LI') {
    lis[idx].className = '';
    lis[target.index].className = 'cur'
    idx = target.index;
    ajax({
      url: 'http://localhost:3000/' + lis[target.index].id,
    }).then(res => {
      const data = res === '404' ? [] : JSON.parse(res);
      let str = '';
      if (data.length) {
        data.forEach(val => {
          str += ` <div class="con_goods">
          <img src="${val.imgs}" alt="">
          <div class="s_name">￥ ${val.pricec}<i>${val.freeShipping}</i> <span>${val.buyers}</span></div>
          <p>${val.name}</p>
          <div class="shop">${val.merchant}<em>${val.shippingPlace}</em></div>
          <input type="button" value="加入购物车" class="addCart"></input>
        </div>`
        });
        goods.innerHTML = str
        goods.onclick = function (eve) {
          const e = eve || window.event;
          const target = e.target || window.event;
          const li = o.$$('.addCart');
          const lis = [...li];
          let i = 0;
          lis.filter(val => val.index = i++)
          if (target.className === 'addCart') {
            const idx = target.index;
            const petCart = cookie.getCookie('petUserD');
            let userTel;
            let id;
            // 获取用户信息
            if (petCart) {
              petCart.split(',').forEach(val => {
                const a = val.split(':');
                if (a[0] === 'tel') {
                  userTel = a[1]
                }
              })
            }
            ; (async () => {
              const obj = {};
              for (let t in data[idx]) {
                obj[t] = data[idx][t]
              }
              console.log(obj)
              first = await ajax({
                url: 'http://localhost:3000/getUser',
                method: 'get',
                data: {
                  userTel,
                  // shopCart: `[${JSON.stringify(obj)}]`
                },
              }).then(res => {
                return JSON.parse(res).data
              });
              console.log(first)
              if (first.length === 0 && !first[0]) {
                obj.num = 1;
                obj.check = true;
                first.push(obj)
                // 用户购物车没有数据，添加数据
                ajax({
                  url: 'http://localhost:3000/userShopCart',
                  method: 'post',
                  data: {
                    userTel,
                    shopCart: `${JSON.stringify(first)}`
                  },
                })
              } else {
                id = data[idx]._id;
                const falg = first.some((val) => {
                  if (val._id === id) {
                    val.num++
                    ajax({
                      url: 'http://localhost:3000/userShopCart',
                      method: 'post',
                      data: {
                        userTel,
                        shopCart: JSON.stringify(first)
                      }
                    })
                  }
                  return val._id === id
                })
                if (!falg) {
                  obj.num = 1;
                  obj.check = true;
                  first.push(obj)
                  // 用户购物车没有数据，添加数据
                  ajax({
                    url: 'http://localhost:3000/userShopCart',
                    method: 'post',
                    data: {
                      userTel,
                      shopCart: `${JSON.stringify(first)}`
                    },
                  })
                }
              }






            }
            )();
          }
        }
      } else {
        goods.innerHTML = str
        goods.onclick = function (eve) {
          const e = eve || window.event;
          const target = e.target || window.event;
          const li = o.$$('.addCart');
          const lis = [...li];
          let i = 0;
          lis.filter(val => val.index = i++)
          if (target.className === 'addCart') {
            const idx = target.index;
            const petCart = cookie.getCookie('petUserD');
            let userTel;
            let id;
            // 获取用户信息
            if (petCart) {
              petCart.split(',').forEach(val => {
                const a = val.split(':');
                if (a[0] === 'tel') {
                  userTel = a[1]
                }
                // if(a[0] === 'uId'){
                //   id = a[1]
                // }
              })
            }
            ; (async () => {
              const obj = {};
              for (let t in data[idx]) {
                obj[t] = data[idx][t]
              }
              first = await ajax({
                url: 'http://localhost:3000/getUser',
                method: 'get',
                data: {
                  userTel,
                  // shopCart: `[${JSON.stringify(obj)}]`
                },
              }).then(res => {
                return JSON.parse(res).data
              });
              console.log(first)
              if (first.length === 0 && !first[0]) {
                obj.num = 1
                first.push(obj)
                // 用户购物车没有数据，添加数据
                ajax({
                  url: 'http://localhost:3000/userShopCart',
                  method: 'post',
                  data: {
                    userTel,
                    shopCart: `${JSON.stringify(first)}`
                  },
                })
              } else {
                id = data[idx]._id;
                const falg = first.some((val) => {
                  if (val._id === id) {
                    val.num++
                    ajax({
                      url: 'http://localhost:3000/userShopCart',
                      method: 'post',
                      data: {
                        userTel,
                        shopCart: JSON.stringify(first)
                      }
                    })
                  }
                  return val._id === id
                })
                if (!falg) {
                  obj.num = 1;
                  first.push(obj)
                  // 用户购物车没有数据，添加数据
                  ajax({
                    url: 'http://localhost:3000/userShopCart',
                    method: 'post',
                    data: {
                      userTel,
                      shopCart: `${JSON.stringify(first)}`
                    },
                  })
                }
              }






            }
            )();
          }
        }
      }
    })
  }
}
